package com.sl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sl.entity.PageResult;
import com.sl.entity.Result;
import com.sl.entity.StatusCode;
import com.sl.pojo.Option;
import com.sl.pojo.Paper;
import com.sl.pojo.PaperQuestions;
import com.sl.pojo.Question;
import com.sl.service.*;
import com.sl.vo.QuestionVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/paper")
public class PaperController {
    @Autowired
    private PaperService paperService;
    @Autowired
    private PaperQuestionsService paperQuestionsService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private OptionService optionService;
    @Autowired
    private QuestionOptionService questionOptionService;

    @PostMapping("/all")
    public Result findAll(){
        List<Paper> all = paperService.all();
        return new Result<Paper>(true, StatusCode.OK,"显示所有：试题卷",all);
    }

    /**
     * 增加一套试题题目,题目为data
     * @param data
     * @return
     */
    @PostMapping("/add")
    public Result addPaper(@RequestBody String data){
        log.info("增加一套试题题目,题目为：" + data);
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSON.parseObject(data);
        String paperStr = jsonObject.getString("paper");
        Paper byPaperName = paperService.findByPaperName(paperStr);
        if (null !=byPaperName){return  new Result(false, StatusCode.ERROR,"此套题已经存在，重新命名"); }
        Paper paper = new Paper();
        paper.setPaper(paperStr);
         paperService.add(paper);
        return new Result<Paper>(true, StatusCode.OK,"增加一套试题题目成功");
    }

    /**
     * 输入试卷号。显示：题、选项。
     * @param data
     * @return
     */
    @PostMapping("/questions")
    public Result paper4Questions(@RequestBody String data){
        log.info("根据试卷ID显示题" + data);
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = jsonObject.getInteger("paperId");
        if(null == id){ return  new Result(false, StatusCode.ERROR,"paperId参数错误"); }
        List<PaperQuestions> paperQuestions = paperQuestionsService.findByPaperId(id);
        List<QuestionVO> voList=new ArrayList<>();
        for (PaperQuestions paperQuestion : paperQuestions) {
            //paperQuestions --->>questionId
            Integer questionId = paperQuestion.getQuestionId();//题ID
            //questionId --->>Question
            Question questionById = questionService.findById(questionId);//题
            String content = questionById.getContent();//
            String type = questionById.getType();//题的类型。choose 和 short
            QuestionVO questionVO = new QuestionVO();
            questionVO.setQuestionId(questionId);//题目ID
            questionVO.setContentVO(content);//题目内容
        //如果中间表不为空。有对应答案。。。。为空的话：返回说明"为空"
            String options="";
            Set<Integer> oidByQids = questionOptionService.findOidByQid(questionId);
            if(null !=oidByQids){
                if(type.equals("choose")){
                        for (Integer oId : oidByQids) {
                            Option option = optionService.findById(oId);
                            String questionOption = option.getQuestionOption();
                            options  +=questionOption + "/";
                    }
                    String optionsSubstring = options.substring(0, options.length() - 1);
                    questionVO.setOption(optionsSubstring);
                }
                else {
                    questionVO.setOption(options);
                }

            }else if(null ==oidByQids){
                questionVO.setOption("请确定题目的类型:choose或short或新增");
            }
            log.info("questionVO" + questionVO);
            voList.add(questionVO);
        }
        PageResult pageResult=new PageResult((long)voList.size(),voList);
        return new Result<Paper>(true, StatusCode.OK,"查看本套试题内容",pageResult);
    }

    //给peper试卷。。加题
    @PostMapping("/addQuestions")
    public Result AddpaperQuestions(@RequestBody String data){
        log.info("给此套试题，增加问题");
        if(StringUtils.isEmpty(data)){ return  new Result(false, StatusCode.ERROR,"参数为空");}
        JSONObject jsonObject = JSON.parseObject(data);
        log.info("data>>>" + jsonObject);
        String paperStr = jsonObject.getString("paper");
        JSONArray questionIds = jsonObject.getJSONArray("questionIds");
        Paper byPaperName = paperService.findByPaperName(paperStr);
        Integer paperId = byPaperName.getId();

        for (Object questionId : questionIds) {
            PaperQuestions paperQuestions = new PaperQuestions();
            paperQuestions.setPaperId(paperId);
            paperQuestions.setQuestionId((Integer)questionId);
            System.out.println(paperQuestions);
            paperQuestionsService.addPaperQuestion(paperQuestions);
        }
        return new Result<Paper>(true, StatusCode.OK,"试题"+paperStr+"增加内容成功");
    }

    //删除中间表重复的。。id主键会一直增大
    @DeleteMapping("/delrepeat")
    public void deleteRepeat(){
        List<PaperQuestions> all = paperQuestionsService.findAll();
        Set<PaperQuestions>  PQSet=new HashSet<>();
        for (PaperQuestions paperQuestions : all) {
            System.out.println("paperQuestions>>" + paperQuestions);
            PaperQuestions newPQ = new PaperQuestions();
            newPQ.setPaperId(paperQuestions.getPaperId());
            newPQ.setQuestionId(paperQuestions.getQuestionId());
            System.out.println("newPQ>>" + newPQ);
            PQSet.add(newPQ);
            paperQuestionsService.deleted(paperQuestions);
        }
        for (PaperQuestions paperQuestions : PQSet) {
            paperQuestionsService.addPaperQuestion(paperQuestions);
        }
        System.out.println(PQSet);
    }

    @DeleteMapping("/deleted")
    public  Result deletePaper(@RequestBody String data ){
        log.info("删除试题" + data);
        Paper paper = JSON.parseObject(data, Paper.class);
        Integer paperId = paper.getId();
        List<PaperQuestions> byPaperId = paperQuestionsService.findByPaperId(paperId);
        if(byPaperId.size() > 0){
            for (PaperQuestions paperQuestions : byPaperId) {
                log.info("删除关联题");
                paperQuestionsService.deleted(paperQuestions);
            }
        }
        System.out.println("paper>>" + paper);
        paperService.deleted(paper);
        return new Result<Paper>(true, StatusCode.OK,"删除试题成功");
    }
}
